<template>
  <div class="one-container">
    <el-tabs v-model="activeTab" class="demo-tabs">
      <el-tab-pane
        :label="tab.task_name"
        :name="tab.task_id"
        :key="index"
        v-for="(tab, index) in relationList"
      ></el-tab-pane>
    </el-tabs>
    <main>
      <!-- 学生列表 -->
      <div class="student-box" v-if="unSubmitList.length">
        <div class="sign-box">
          <span class="left">未完成：{{ unSubmitList.length }}人</span>
          <p class="right flex">
            <span class="hover" @click="isShowNameList = !isShowNameList"
              >{{ isShowNameList ? '收起' : '展开' }}名单</span
            >
          </p>
        </div>
        <template v-if="isShowNameList">
          <div class="student-list flex">
            <span
              v-for="(student, studentIndex) in unSubmitList"
              :key="studentIndex"
              class="student-item"
            >
              {{ student.student_name }}
            </span>
          </div>
        </template>
      </div>
      <div class="search-box">
        <el-input
          class="class-name"
          placeholder="学生姓名"
          :suffix-icon="Search"
          v-model="search.studentName"
        ></el-input>
        <div class="right-rate">
          <p class="tip">任务正确率</p>
          <div class="input-box">
            <el-input-number
              placeholder="最低"
              :controls="false"
              :min="0"
              v-model="search.low_rate"
            ></el-input-number>
            <span class="separator">—</span>
            <el-input-number
              placeholder="最高"
              :controls="false"
              :max="100"
              v-model="search.high_rate"
            ></el-input-number>
          </div>
        </div>
        <el-select
          class="type"
          placeholder="全部题型"
          v-model="search.type"
          popper-class="question-type-popper"
        >
          <el-option
            v-for="item in questionType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        /></el-select>
        <span
          class="primary-text table-target"
          :class="{ 'disabled-text': selectionList.length === 0 }"
          @click="addTargetClass"
        >
          <img
            v-if="selectionList.length === 0"
            class="add-icon"
            src="@/assets/images/assignment/add-disabled-icon.png"
          />
          <img
            v-else
            class="add-icon"
            src="@/assets/images/assignment/add-icon.png"
          />

          加入靶向班</span
        >
      </div>
      <el-table
        ref="tableRef"
        :data="studentList"
        empty-text="暂无数据"
        @selection-change="handleSelectionChange"
        class="course-score-table"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" align="center" label="序号" width="100" />
        <el-table-column prop="student_name" align="center" label="姓名" />
        <el-table-column prop="submit" align="center" label="完成情况">
          <template #default="scope">
            <el-tag :type="scope.row.submit ? 'primary' : 'info'">
              {{ scope.row.submit ? '已提交' : '未提交' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="teacher_correct" align="center" label="批改状态">
          <template #default="scope">
            <span v-if="!scope.row.submit">--</span>

            <el-tag
              v-else
              :type="scope.row.teacher_correct == -1 ? 'danger' : 'success'"
            >
              {{ scope.row.teacher_correct === -1 ? '未批改' : '已完成' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="score_rate"
          align="center"
          label="正确率"
          :sortable="true"
        >
          <template #default="scope">
            <span v-if="!scope.row.submit">--</span>
            <span v-else> {{ (scope.row.score_rate * 100).toFixed(0) }}% </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="submit_time"
          align="center"
          label="提交时间"
          :sortable="true"
        >
          <template #default="scope">
            <span v-if="!scope.row.submit">--</span>
            <span v-else>{{
              dayjs(scope.row.submit_time).format('YYYY-MM-DD HH:mm:ss')
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="question_count" align="center" label="题目详情">
          <template #default="scope">
            <span v-if="!scope.row.submit">
              {{ scope.row.question_count }}道 详情
            </span>
            <el-button v-else type="primary" text @click="toDetail(scope.row)">
              {{ scope.row.question_count }}道 详情
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="action" align="center" label="操作">
          <template #default="scope">
            <el-popconfirm
              title="确定删除？"
              @confirm="onDeleteTask(scope.row)"
            >
              <template #reference>
                <el-button> 删除练习 </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </main>
    <CreateTargetClass
      :visible="targetVisible"
      @close="closeTargetDialog"
      :currentGrade="classSelect.grade_id"
      :studentList="targetClassStudents"
      :teacherId="authStore.userInfo.userId"
      :schoolId="authStore.userInfo.school_id"
    ></CreateTargetClass>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import {
  getRelationTask,
  getTaskStudentResponse,
  deleteStudentTask
} from '@/apis/assignment'
import { debounce } from '@/utils/debounce'
import { Search } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth-store.js'
import CreateTargetClass from '@/views/workbench/components/CreateTargetClass.vue'

const authStore = useAuthStore()
const props = defineProps({
  taskInfo: {
    type: Object,
    required: true
  },
  classSelect: {
    required: false
  }
})

const router = useRouter()
const questionType = [
  {
    label: '全部题型',
    value: ''
  },
  {
    label: '主观题',
    value: '1'
  },
  {
    label: '客观题',
    value: '2'
  }
]

const relationList = ref([])
const activeTab = ref()
const unSubmitList = ref([]) // 未提交学生
const isShowNameList = ref(false)
const tableRef = ref()
const selectionList = ref([])
const search = ref({
  studentName: '',
  low_rate: undefined,
  high_rate: undefined,
  type: ''
})
const studentList = ref([])

// 获取当前举一反三列表
const getTaskStudentResponseInfo = async () => {
  const res = await getTaskStudentResponse({
    task_id: activeTab.value,
    student_name: search.value.studentName,
    low_rate: search.value.low_rate,
    high_rate: search.value.high_rate,
    question_type: search.value.type
  })

  unSubmitList.value = res.data.un_submit_list.list || []
  studentList.value = res.data.student_info.list || []
}

// 获取举一反三任务列表
const getRelationTaskInfo = async () => {
  const res = await getRelationTask({
    relation_task_id: props.taskInfo.taskId
  })
  relationList.value = res.data || []
  if (relationList.value.length) {
    activeTab.value = relationList.value[0].task_id
  }
}

const targetClassStudents = ref([])
const targetVisible = ref(false)
const addTargetClass = from => {
  targetClassStudents.value = []

  if (!selectionList.value.length) {
    ElMessage.warning('请先选择学生！')
    return
  }
  targetClassStudents.value = selectionList.value
  targetVisible.value = true
}
const closeTargetDialog = val => {
  targetVisible.value = false
  if (val === 'refresh') tableRef.value && tableRef.value.clearSelection()
}
const handleSelectionChange = val => {
  selectionList.value = (val || []).map(student => {
    return {
      studentName: student.student_name,
      key: student.student_id
    }
  })
}

const onDeleteTask = async param => {
  await deleteStudentTask({
    task_id: activeTab.value,
    student_id: param.student_id
  })
  ElMessage.success('删除成功！')
  getTaskStudentResponseInfo()
}

const toDetail = param => {
  router.push({
    name: 'oneThreeDetail',
    query: {
      task_id: activeTab.value,
      taskInfo: JSON.stringify(param)
    }
  })
}

watch(
  [
    () => activeTab.value,
    () => search.value.studentName,
    () => search.value.low_rate,
    () => search.value.high_rate,
    () => search.value.type
  ],
  () => {
    debounce(() => {
      getTaskStudentResponseInfo()
    }, 500)
  }
)
const initData = () => {
  getRelationTaskInfo()
}
initData()
</script>

<style lang="less" scoped>
.one-container {
  background-color: #fff;
  margin-bottom: 20px;
  padding: 20px;
  .student-box {
    height: fit-content;
    flex-shrink: 0;
    margin-bottom: 20px;
    background-color: #fdf8f1;

    .sign-box {
      height: 36px;
      text-align: center;
      color: #ffae10;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-right: 16px;

      .left {
        line-height: 36px;
        height: 36px;
        background: #ffae101a;
        padding: 0 15px;
        font-size: 14px;
      }
      .right {
        color: #5466e7;
        gap: 20px;
        .add-icon {
          width: 16px;
          margin-right: 4px;
        }
      }
    }

    .student-list {
      padding: 20px;
      flex-wrap: wrap;
      gap: 10px;

      .student-item {
        color: #333;
        padding: 0 4px;
      }
    }
  }
  .table-target {
    position: absolute;
    right: 20px;

    &.disabled-text {
      cursor: not-allowed;
      color: #72757e !important;
    }
  }
  .primary-text {
    cursor: pointer;
    margin-left: 30px;
    color: #5466e7;
    font-size: 16px;
    display: inline-flex;
    align-items: center;

    .add-icon {
      width: 14px;
      margin-right: 8px;
    }
  }
  .search-box {
    height: fit-content;
    flex-shrink: 0;
    display: flex;
    gap: 40px;
    margin-bottom: 20px;

    :deep(.class-name) {
      width: 220px;
      height: 30px !important;

      .el-input__wrapper {
        border-radius: 0;
        box-shadow: none;
        border: 1px solid #b7b8bb;

        .el-input__inner {
          font-size: 14px;

          &::placeholder {
            font-size: 14px;
          }
        }
      }
    }
    .right-rate {
      display: flex;
      align-items: center;
      border: 1px solid #b7b8bb;
      height: 30px;

      * {
        font-size: 14px;
      }

      .tip {
        padding: 0 10px;
        font-size: 14px;
        color: #333333;
        width: fit-content;
        white-space: nowrap;
        border-right: 1px solid #b7b8bb;
        height: 100%;
        line-height: 30px;
      }

      .separator {
        color: #b7b8bb;
      }

      .input-box {
        .el-input-number {
          width: 100px;
          height: 28px;

          :deep(.el-input__wrapper) {
            border-radius: 0;
            // border: 1px solid #b7b8bb;
            border-left: unset;
            border-right: unset;
            box-shadow: none;
          }
        }
      }
    }

    .type {
      width: 108px;

      :deep(.el-select__wrapper) {
        border-radius: 0;
        box-shadow: none;
        border: 1px solid #b7b8bb;
      }
    }
  }
  .course-score-table {
    flex: 1;
    overflow-y: scroll;

    .finish-row {
      gap: 10px;
    }

    .not-finish {
      color: #b7b8bb;
    }

    .wrong-label {
      display: inline-block;
      color: #ea4338;
      border: 1px solid #ea4338;
      padding: 0 8px;
      height: 24px;
      line-height: 24px;
      margin-right: 4px;
    }

    /* stylelint-disable ebag/selector-class-pattern */
    :deep(.cell) {
      line-height: 40px !important;

      .el-table__expand-icon {
        display: none;
      }
    }

    :deep(.caret-wrapper) {
      height: 12px;
    }

    :deep(.el-table__header) {
      .el-table__cell {
        background-color: #f2f4f9;
      }
    }
  }

  .not-start {
    display: flex;
    flex-direction: column;
    align-items: center;
    height: 600px;
    justify-content: center;

    img {
      width: 254px;
    }

    .tip {
      color: #333;
      font-size: 14px;
      margin-top: 20px;
    }
  }
}
</style>
